package cn.edu.nankai.bookstore.dao.impi;

import cn.edu.nankai.bookstore.utils.DataPool;

import java.sql.*;

public class GenericBaseDao {

    protected Connection conn;
    protected PreparedStatement pstmt;
    protected ResultSet rs;
    protected int result = 0;

    public void getConnection() throws SQLException {
        conn = DataPool.ds.getConnection();
    }

    public void closeAll() throws SQLException {
        if (rs != null && !rs.isClosed()) {
            rs.close();
        }
        if (pstmt != null && !pstmt.isClosed()) {
            pstmt.close();
        }
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
        if (result != 0) {
            result = 0;
        }
    }

    public void executeInsert(String sql , Object... params) throws  SQLException{
        pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        if (params != null) {
            for (int i = 0; i < params.length; ++i) {
                pstmt.setObject(i + 1, params[i]);
            }
        }
        pstmt.executeUpdate();
        rs = pstmt.getGeneratedKeys();
        if (rs.next()) {
            result = rs.getInt(1);
        }
    }

    public void executeUpdate(String sql, Object... params) throws SQLException {
        pstmt = conn.prepareStatement(sql);
        if (params != null) {
            for (int i = 0; i < params.length; ++i) {
                pstmt.setObject(i + 1, params[i]);
            }
        }
        result=pstmt.executeUpdate();
    }

    public void executeQuery(String sql, Object... params) throws SQLException {
        pstmt = conn.prepareStatement(sql);
        if (params != null) {
            for (int i = 0; i < params.length; ++i) {
                pstmt.setObject(i + 1, params[i]);
            }
        }
        rs = pstmt.executeQuery();
    }
}
